package com.lhkk.inventoryvehicle.common

import java.util.concurrent.*

/**
 * 程池单例
 */
object ThreadPoolInstance {

    private var singleThreadExecutor: ExecutorService? = null
    private var fixedThreadPool: ExecutorService? = null
    private var threadPoolExecutor: ThreadPoolExecutor? = null


    /**
     * 获取基本线程池
     * keepAliveTime设置为0，非核心线程空闲时会被立即回收
     */
    fun getThreadPoolExecutor(): ThreadPoolExecutor? {
        synchronized(ThreadPoolInstance::class.java) {
            if (threadPoolExecutor == null) {
                threadPoolExecutor = ThreadPoolExecutor(5,
                    10,
                    0,
                    TimeUnit.SECONDS,
                    LinkedBlockingQueue(Int.MAX_VALUE))
            }
        }
        return threadPoolExecutor
    }

    /**
     * 获取单线程池
     */
    fun getSingleThreadExecutor(): ExecutorService? {
        synchronized(ThreadPoolInstance::class.java) {
            if (singleThreadExecutor == null) {
                singleThreadExecutor = Executors.newSingleThreadExecutor()
            }
        }
        return singleThreadExecutor
    }

    /**
     * 获取固定核心数线程池
     */
    fun getFixedThreadPool(): ExecutorService? {
        synchronized(ThreadPoolInstance::class.java) {
            if (fixedThreadPool == null) {
                fixedThreadPool = Executors.newFixedThreadPool(5)
            }
        }
        return fixedThreadPool
    }
}